package banco;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import basicas.Aluno;
import dao.DAO;
import dao.DAOException;

public class AcoesBancoAluno extends DAO {
	public Aluno inserir(Aluno aluno) {
        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            con = getConnection(true);
            pstmt = con.prepareStatement("INSERT INTO aluno (matricula, nome, cpf) VALUES (?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
            pstmt.setInt(1, aluno.getMatricula());
            pstmt.setString(2, aluno.getNome());
            pstmt.setString(3, aluno.getCpf());
            
            pstmt.executeUpdate();
            rs = pstmt.getGeneratedKeys();
            if (rs.next()) {
            	aluno.setId(rs.getInt(1));
            }


        } catch (SQLException ex) {
            throw new DAOException(ex);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }

                if (pstmt != null) {
                    pstmt.close();
                }

                if (con != null) {
                    con.close();
                }
            } catch (SQLException ex) {
                throw new DAOException(ex);
            }
        }
        return aluno;
	}
	
	public Aluno procurarPorMatricula(String matricula) {
        Connection con = null;
        ResultSet rs = null;
        Aluno aluno = null;
        PreparedStatement pstmt = null;

        try {
            con = getConnection(true);
            pstmt = con.prepareStatement("SELECT id, matricula, nome, cpf, debito FROM aluno WHERE matricula = ?");
            pstmt.setString(1, matricula);
            pstmt.execute();
            rs = pstmt.getResultSet();
            if (rs.next()) {
            	aluno = new Aluno(rs.getInt("matricula"), rs.getString("nome"));
            	aluno.setId(rs.getInt("id"));
            	aluno.setCpf(rs.getString("cpf"));
            	aluno.setDebito(rs.getFloat("debito"));
            }

        } catch (SQLException ex) {
            throw new DAOException(ex);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }

                if (pstmt != null) {
                    pstmt.close();
                }

                if (con != null) {
                    con.close();
                }
            } catch (SQLException ex) {
                throw new DAOException(ex);
            }
        }

        return aluno;
	}
	
	
}
